import React, { Component } from 'react'

// 跨组件之间的数据传递
const MyContext = React.createContext({name:'默认值',age:18});

class ChildOne extends Component {
    render() {
        return (
            <>
                <ChildTwo></ChildTwo>
            </>
        )
    }
}

class ChildTwo extends Component {
    render() {
        return (
            <>
                {this.context.name} -- {this.context.age}
            </>
        )
    }
}
ChildTwo.contextType = MyContext;  //这里会重新创建一个context实例，所以在类中可以使用this.context

{/* 函数式组件使用UserContext.Consumer接收传递的值 */}

function ChildFn() {
    return (
        <div>
            <MyContext.Consumer>
                {
                    (value => {
                        return (
                            <div>
                                {value.name} -- {value.age}
                            </div>
                        )
                    })
                }
            </MyContext.Consumer>
        </div>
    )
}

export default class Parent extends Component {
  render() {
    return (
      <>
        <MyContext.Provider value={{name:'provider提供的值',age:16}}>
            <ChildOne />
            <ChildFn></ChildFn>
        </MyContext.Provider>
        {/* 这种情况会使用默认值 */}
        <ChildOne />
        <ChildFn></ChildFn>
      </>
    )
  }
}
